from django.middleware.common import MiddlewareMixin
import re
from django.shortcuts import HttpResponse
from django.conf import settings


class RbacMiddleware(MiddlewareMixin):

    # 请求拦截
    def process_request(self, request):
        # 对客户端发起的url请求进行权限验证
        current_url = request.path_info
        for white_url in settings.WHITE_LIST:
            if re.fullmatch(white_url, current_url):
                # if white_url == current_url:
                # 中间键中返回None即表示可以继续访问 不拦截
                return None
        permission_list = request.session.get(settings.CRM_PERMISSION_SESSION_KEY)
        # 用户未登录
        if not permission_list:
            return HttpResponse("未获取到用户权限，请先登录")
        flag = False
        for url in permission_list:
            reg = "^%s$" % url
            if re.match(reg, current_url):
                flag = True
                break

        if not flag:
            return HttpResponse("无权访问")
